package com.bestdo.t;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Paths;

import org.apache.commons.io.IOUtils;

/**
 * 图片处理
 * 
 * @author liuhui
 *
 */
public class ImageProcessor {

	/**
	 * ImageMageck安装路径 / 加入path则为空
	 */
	private static final String MAGICK_BASE_PATH = "";
	// 水印文件
	private static final String WATER_FILENAME = "";

	private static final Charset CHARSET = Charset.forName("UTF-8");

	private static boolean NOT_WINDOS = false;
	static {
		NOT_WINDOS = !";".equals(File.pathSeparator);
	}

	public static class ImageInfo {
		private Integer width;
		private Integer height;
		private String extension;
		private Long size;
		private String colorspace;

		public Integer getWidth() {
			return width;
		}

		public void setWidth(Integer width) {
			this.width = width;
		}

		public Integer getHeight() {
			return height;
		}

		public void setHeight(Integer height) {
			this.height = height;
		}

		public String getExtension() {
			return extension;
		}

		public void setExtension(String extension) {
			this.extension = extension;
		}

		public Long getSize() {
			return size;
		}

		public void setSize(Long size) {
			this.size = size;
		}

		public String getColorspace() {
			return colorspace;
		}

		public void setColorspace(String colorspace) {
			this.colorspace = colorspace;
		}

	}

	private static String executeCmd(String cmd) {
		System.out.println(cmd);
		InputStream br = null;
		try {
			Process process = null;
			if (NOT_WINDOS) {
				process = Runtime.getRuntime().exec(cmd);
			} else {
				String[] comman = { "cmd.exe", "/c", cmd };
				process = Runtime.getRuntime().exec(comman);
			}

			br = process.getErrorStream();

			byte[] stream = IOUtils.toByteArray(br);

			String reslut = new String(stream, CHARSET);
			if (!reslut.isEmpty()) {
				// throw new SystemException(ServiceResultEnum.IMG_DEAL_FALLURE);
				throw new RuntimeException(reslut.toString());
			}
			br = process.getInputStream();

			stream = IOUtils.toByteArray(br);
			reslut = new String(stream, CHARSET);
			return reslut;
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				// throw new SystemException(e);
			}
		}
	}

	/**
	 * 获取图片信息 identify -format "%w,%h,%m,%b,%r" path
	 * 
	 * @param srcFilename
	 *            图片路径
	 * @return
	 */
	public static ImageInfo identify(String srcFilename) {
		String cmd = MAGICK_BASE_PATH + "identify -format \"%w,%h,%m,%b,%r\"   " + srcFilename;
		String result = executeCmd(cmd);
		ImageInfo info = new ImageInfo();
		String[] str = result.split(",");
		int i = 0;
		info.setWidth(Integer.parseInt(str[i++]));
		info.setHeight(Integer.parseInt(str[i++]));
		info.setExtension(str[i++]);
		info.setSize(Long.parseLong(str[i++].replace("B", "")));
		info.setColorspace(str[i++]);
		return info;
	}

	/**
	 * 给图片加水印 composite -watermark opacity -gravity position waterFilePath iFileName iFileName
	 * 
	 * @param inFilePath
	 *            源图片路径
	 * @param outFilePath
	 *            处理后图片路径
	 * @param waterFilePath
	 *            水印图历经
	 * @param opacity
	 *            透明度
	 * @param position
	 *            水印位置
	 */
	private static void waterMarker(String srcFilename, String destFilename, String waterFilePath, int opacity, String position) {
		String cmd = MAGICK_BASE_PATH + "composite -watermark " + opacity + " -gravity " + position + " " + waterFilePath + " " + srcFilename + " " + destFilename;
		executeCmd(cmd);
	}

	public static void waterMarker(String srcFilename, String destFilename) {
		waterMarker(srcFilename, destFilename, WATER_FILENAME, 30, "SouthEast");
	}

	public static void waterMarker(String srcFilename) {
		waterMarker(srcFilename, srcFilename);
	}

	/**
	 * 按宽高比例缩放图片，不足则补白背景
	 * 
	 * @param inFilePath
	 *            源图
	 * @param outFilePath
	 *            结果
	 * @param width
	 *            缩略宽度
	 * @param height
	 *            缩略高度 convert 1060.jpg -resize 300x300 bbb.jpg
	 */
	public static void resize(String inFilePath, String outFilePath, int width, int height) {
		checkFileParent(outFilePath);
		String cmd = MAGICK_BASE_PATH + "convert " + inFilePath + " -resize " + width + "x" + height + " -background white -gravity center -extent " + width + "x" + height + " " + outFilePath;
		executeCmd(cmd);
	}

	/**
	 * 按绝对宽高缩放图片
	 * 
	 * @param inFilePath
	 *            源图
	 * @param outFilePath
	 *            结果
	 * @param width
	 *            缩略宽度
	 * @param height
	 *            缩略高度 convert 1060.jpg -resize 300x300! bbb.jpg
	 */
	public static void resizeAbsolutely(String inFilePath, String outFilePath, int width, int height) {
		checkFileParent(outFilePath);
		String cmd = MAGICK_BASE_PATH + "convert " + inFilePath + " -resize " + width + "x" + height + "! " + outFilePath;
		executeCmd(cmd);
	}

	/**
	 * 按比例缩放图片，宽度限制为 width，高度自适应
	 * 
	 * @param inFilePath
	 * @param outFilePath
	 * @param width
	 */
	public static void resizeAutoHeight(String inFilePath, String outFilePath, int width) {
		checkFileParent(outFilePath);
		String cmd = MAGICK_BASE_PATH + "convert " + inFilePath + " -resize " + width + " " + outFilePath;
		executeCmd(cmd);
	}

	/**
	 * 按比例缩放图片，宽度限制为 width，高度自适应
	 * 
	 * @param inFilePath
	 * @param outFilePath
	 * @param width
	 */
	public static void resizeAutoWidth(String inFilePath, String outFilePath, int height) {
		checkFileParent(outFilePath);
		String cmd = MAGICK_BASE_PATH + "convert " + inFilePath + " -resize x" + height + " " + outFilePath;
		executeCmd(cmd);
	}

	/**
	 * 简单处理图片 convert -strip -quality 75% path path
	 * 
	 * @param srcFilename
	 *            路径
	 */
	public static void process(String srcFilename, String destFilename) {
		checkFileParent(destFilename);
		String cmd = MAGICK_BASE_PATH + "convert -strip -quality 75% " + srcFilename + " " + destFilename;
		executeCmd(cmd);
	}

	public static void process(String srcFilename) {
		process(srcFilename, srcFilename);
	}

	/**
	 * 图片剪裁
	 * 
	 * @param inFilePath
	 * @param outFilePath
	 * @param x
	 * @param y
	 * @param width
	 * @param height
	 */
	public static void crop(String inFilePath, String outFilePath, int x, int y, int width, int height) {
		checkFileParent(outFilePath);
		String cmd = MAGICK_BASE_PATH + "convert " + inFilePath + " -crop " + width + "x" + height + "+" + x + "+" + y + " " + outFilePath;
		executeCmd(cmd);
	}

	private static void checkFileParent(String path) {
		File parentFile = new File(path).getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdir();
		}
	}

	public static void main(String[] args) throws Exception {
		// process("/Users/zhaokuner/Desktop/share_knowledge.jpeg");
		InputStream br = null;
		Process process = Runtime.getRuntime().exec("convert", new String[] { "  -clip " }, Paths.get("./").toFile());
		br = process.getErrorStream();
		System.out.println(br.available());
		byte[] stream = IOUtils.toByteArray(br);

		String reslut = new String(stream, CHARSET);
		System.out.println(reslut);
		if (!reslut.isEmpty()) {
			System.out.println("-------");
		}
		br = process.getInputStream();

		stream = IOUtils.toByteArray(br);
		reslut = new String(stream, CHARSET);
		System.out.println("it's over!~~");
	}

}
